<template>
  <div class="user-container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片导航区域 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 搜素添加区域 -->
        <el-col :span="9">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加按钮区域 -->
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="UserList" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>

        <el-table-column prop="username" label="姓名"> </el-table-column>

        <el-table-column prop="email" label="邮箱"> </el-table-column>

        <el-table-column prop="mobile" label="电话"> </el-table-column>

        <el-table-column prop="role_name" label="角色"> </el-table-column>

        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userstatechanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              effect="dark"
              content="修改内容"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="gettext(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip
              effect="dark"
              content="删除按钮"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserbyid(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="角色分配"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setuser(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- @close是监听对话框的关闭时自动触发的事件 -->
      <!-- 对话框区域 -->
      <el-dialog
        title="添加用户"
        :visible.sync="adddialogVisible"
        width="50%"
        @close="dialogclear"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="formuser"
          :rules="fromrules"
          ref="ruleFormRef"
          label-width="80px"
        >
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formuser.username"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input v-model="formuser.password"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="formuser.email"></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="formuser.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addduser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="eddialogVisible"
        width="50%"
        @close="editdialogclear"
      >
        <!-- 修改用户信息的内容 -->
        <el-form
          :model="eidtFrom"
          :rules="eidtFromRes"
          ref="ruleFormRef"
          label-width="80px"
        >
          <!-- 修改信息的用户名 -->
          <el-form-item label="用户名">
            <el-input v-model="eidtFrom.username" :disabled="true"></el-input>
          </el-form-item>

          <!-- 修改信息的用户邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="eidtFrom.email"></el-input>
          </el-form-item>
          <!-- 修改用户的手机号 -->
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="eidtFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="eddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="giteddUser">确 定</el-button>
        </span> </el-dialog
      >'
      <!-- 分配角色的对话框 -->
      <el-dialog
        title="角色分配"
        :visible.sync="userdialogVisible"
        width="50%"
        @close="setdialogclear"
      >
        <div>
          <p>当前的用户：{{ userinfo.username }}</p>
          <p>当前的角色：{{ userinfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="userid" placeholder="请选择">
              <el-option
                v-for="item in newuserlist"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveroleinfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      UserList: [],
      total: 0,
      // 对话框的显示和隐藏
      adddialogVisible: false,
      //修改用户信息的对话框的显示和隐藏
      eddialogVisible: false,
      // 查询到的用户信息保存
      eidtFrom: {},
      // 修改用户信息规则
      eidtFromRes: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (
                /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value) ==
                false
              ) {
                callback(new Error("请输入正确的邮箱"));
              } else {
                callback();
              }
            },
            trigger: "blur", //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
                  value
                ) == false
              ) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur", //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
          },
        ],
      },
      formuser: {
        username: "",
        userpaw: "",
        useremail: "",
        usermobile: "",
      },
      fromrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名至少3位至多10位",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (/^[^_][a-zA-Z0-9_\u4e00-\u9fa5]*[^_]$/.test(value) == false) {
                callback(new Error("用户名不能有空格开头结尾不能有下划线"));
              } else {
                callback();
              }
            },
            trigger: "blur", //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码至少6位至多15位",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (/^\w+$/.test(value) == false) {
                callback(new Error("密码不能有空格开头结尾不能有下划线"));
              } else {
                callback();
              }
            },
            trigger: "blur", //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (
                /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value) ==
                false
              ) {
                callback(new Error("请输入正确的邮箱"));
              } else {
                callback();
              }
            },
            trigger: "blur", //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (
                /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
                  value
                ) == false
              ) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur", //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
          },
        ],
      },
      //角色分配的对话框展示与隐藏
      userdialogVisible: false,
      //需要被分配角色用户信息
      userinfo: {},
      //所有角色的数据列表
      newuserlist: [],
      //已选中的所修改的用户id
      userid: "",
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.erroe("获取用户列表失败");
      }
      this.UserList = res.data.users;
      this.total = res.data.total;
    },
    // 监听pagesize改变的事件
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getUserList();
    },
    // 监听页码值改变的事件
    handleCurrentChange(newpagesize) {
      this.queryInfo.pagenum = newpagesize;
      this.getUserList();
    },
    // 用户查找方法
    async userstatechanged(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        return this.$message.erroe("更新状态失败");
      }
      this.$message.success("更新用户状态成功");
    },
    // 对话框关闭清空里边的状态
    dialogclear() {
      this.$refs.ruleFormRef.resetFields();
    },
    //  对对话框里边的内容预效验
    addduser() {
      this.$refs.ruleFormRef.validate(async (value) => {
        if (!value) return;
        //添加新用户
        const { data: res } = await this.$http.post("users", this.formuser);

        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户失败");
        this.adddialogVisible = false;
        this.getUserList();
      });
    },
    // 修改用户信息
    async gettext(id) {
      this.eddialogVisible = true;
      // console.log(id)
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.erroe("修改信息失败");
      }
      // this.$message.success("修改信息成功");
      this.eidtFrom = res.data;
    },
    // 监听修改用户修改对话框
    editdialogclear() {
      this.$refs.ruleFormRef.resetFields();
    },
    // 预效验修改内容并提交
    giteddUser() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.eidtFrom.id,
          {
            email: this.eidtFrom.email,
            mobile: this.eidtFrom.mobile,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.erroe("更改用户信息失败");
        }
      });
      this.eddialogVisible = false;
      this.getUserList();
      this.$message.success("更改用户信息成功");
    },
    // 根据ID删除用户的信息
    async removeUserbyid(id) {
      // 弹框询问是否删除
      const delUser = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
        // 如果用户确认删除，返回字符串confirm
        // 如果用户取消删除，返回字符串cancel
      ).catch((err) => err);
      // console.log(delUser)
      if (delUser !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除用户失败");
      }
      this.$message.success("删除用户成功");
      this.getUserList();
    },
    //展示角色分配的对话框
    async setuser(userinfo) {
      this.userinfo = userinfo;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.newuserlist = res.data;
      this.userdialogVisible = true;
    },
    //点击分配角色
    async saveroleinfo() {
      if (!this.userid) {
        return this.$message.error("请选择要分配的角色");
      }
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        { rid: this.userid }
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("角色分配失败");
      }
      this.$message.success("更新角色成功");
      this.getUserList();
      this.userdialogVisible = false;
    },
    //监听角色对话框
    setdialogclear() {
      this.userid = "";
      this.userinfo = {};
    },
  },
};
</script>

<style>
</style>